/**
 * 
 */
package com.glela.common.util;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author liujie
 *
 */
public class JsonUtil {

	private static final ObjectMapper MAPPER = new ObjectMapper().setTimeZone(TimeZone.getDefault());

	/**
	 * javabean convert to json
	 * 
	 * @param obj
	 * @return string for json
	 * @throws IOException
	 */
	public static String toJson(Object obj) throws IOException {
		return MAPPER.writeValueAsString(obj);
	}

	/**
	 * json convert to javabean
	 * 
	 * @param json
	 * @param clz
	 * @return
	 * @throws IOException
	 */
	public static <T> T toBean(String json, Class<T> clz) throws IOException {
		return MAPPER.readValue(json, clz);
	}

	/**
	 * json convert to collections for javabean
	 * <p>
	 * 如将[{"id":1,"name":"name1"},{"id":2,"name":"name2"}] 转为List<object>
	 * 
	 * @param json
	 * @param typeRef: 如new TypeReference<List<object>>(){}
	 * @return
	 * @throws IOException
	 */
	@SuppressWarnings("rawtypes")
	public static Object toBeans(String json, TypeReference typeRef) throws IOException {
		return MAPPER.readValue(json, typeRef);
	}

	/**
	 * 将JAVA的MAP转换成JSON字符串， 只转换第一层数据
	 * 
	 * @param map
	 * @return
	 */
	public static String simpleMapToJsonStr(Map<?, ?> map) {
		if (map == null || map.isEmpty()) {
			return "null";
		}
		String jsonStr = "{";
		Set<?> keySet = map.keySet();
		for (Object key : keySet) {
			jsonStr += "\"" + key + "\":\"" + map.get(key) + "\",";
		}
		jsonStr = jsonStr.substring(0, jsonStr.length() - 1);
		jsonStr += "}";
		return jsonStr;
	}

	public static void main(String[] args) {
		HashMap<Object, Object> hashMap = new HashMap<>();
		hashMap.put(1, 3);
		try {
			String json = JsonUtil.toJson(hashMap);
			System.out.println(json);
			System.out.println(JsonUtil.toBean(json, Map.class));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static String getSuccessJsonStr(String message, Object data) {
		JSONObject json = new JSONObject();
		json.put("success", true);
		json.put("message", message);
		json.put("data", data);
		json.put("code", 10000);
		return json.toJSONString();
	}

	public static String getFailJsonStr(String errorMsg) {
		JSONObject json = new JSONObject();
		json.put("success", false);
		json.put("message", errorMsg);
		json.put("code", 20000);
		return json.toJSONString();
	}
}
